/**
 * 公共导航组件
 */

import React from 'react';
import { Button, message, Tooltip } from 'antd';
import { Util, temperature } from 'tools/index';
import { $http } from 'containers/config/https';
import ShowComponentModal from './ShowComponentModal';
import fetchJsonp from 'fetch-jsonp';
import '../style/index.less';

const appointment = require('../../../assets/images/img/appointment.png');
const history = require('../../../assets/images/img/history.png');
const hospital = require('../../../assets/images/img/hospital.png');
const inspect = require('../../../assets/images/img/inspect.png');
const patho = require('../../../assets/images/img/patho.png');
const records = require('../../../assets/images/img/records.png');
const textReport = require('../../../assets/images/img/textReport.png');
const infectious = require('../../../assets/images/img/infectious.png');
const diagnosis = require('../../../assets/images/img/diagnosis.png');
const information = require('../../../assets/images/img/information.png');
const productionBook = require('../../../assets/images/img/productionBook.png');//产检本
const resultTarget = require('../../../assets/images/img/resultTarget.png');//检验结果第三方
const doctorAdviceFind = require('../../../assets/images/img/doctorAdviceFind.png');//医嘱查询
const temperate = require('../../../assets/images/img/icon_temperaturelist.png');
const pacsimg = require('../../../assets/images/img/pacsimg.png');//pacs图像
const surgicalapply = require('../../../assets/images/img/surgicalapply.png');//手术申请

export default class ShowCommonNavigationPage extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        var titleData = JSON.parse(sessionStorage.getItem('titleData'));
        this.state = {
            total: 0,
            page: 1,
            pageSize: 10,
            current: 3,
            isShowOutPatientModal: true,
            isShowTriageSystemModal: true,
            userData: userData,
            patientData: patientData,
            titleData: titleData,
            openIdLocalId: "000005",
            password: "56f9c6690d1edc97e7a55de96c4b3a1488fe0fe46748b00c1fa15b36",
            service: "http://120.79.237.79:8086/jumper-cs-nt/nt/personInfo/toPersonIndex",
            manualId: "37150200200000131",
        }
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    componentDidMount() {
        this.setState({
            current: this.props.current,
        })
        this.loadData()
    }

    loadData() {
        var params = {
            params: [{
                GroupDr: this.state.userData.groupID,
                LocDr: this.state.userData.locID,
                Type: 3
            }]
        }
        $http.post('urlS', this, {
            code: '3001',
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({ doctorData: res.result });
                } else {
                    this.setState({ doctorData: [] });
                }
            }
        })
    }

    openWindowBySubTab(data) {
        var { openWindowBySubTab } = this.props;
        openWindowBySubTab && openWindowBySubTab(data)
    }

    hashROuter(code) {
        // this.props.history.push('./03050002/01')
        var { hashROuter } = this.props;
        hashROuter && hashROuter(code);
    }

    saveDiagnosisMsg(id) {
        this.setState({
            current: id
        })
    }

    change(e) {
        this.setState({
            current: e,
            isShowOutPatientModal: true
        })
    }

    //隐藏弹出框
    hideModal(name = 'isShowComponentModal') {
        this.setState({
            [name]: false,//将所有参数置为false
        }, () => {
            if (this.state.dataSource && this.state.dataSource.code == '03050087') {
                var { loadPatientData } = this.props;
                loadPatientData && loadPatientData()
            }
        });
    }

    //公共动态弹框
    showComponentModal(data) {
        console.log('data', data)
        if (data.code == "03050047") {
            this.setState({
                isShowComponentModal: false,
                dataSource: {}
            }, () => {
                let data = {
                    params: [{
                        admID: sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
                        // admID:48,
                    }]
                }
                $http.post('urlS', this, {
                    code: '03050149',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.setState({
                                manualId: res.result.manualId
                            }, () => {
                                const { openIdLocalId, password, service, manualId } = this.state
                                service.replace(/\&/g, "%26")
                                let url = "120.79.237.79:8081/cas/login?auto=true&openIdLocalId=" + openIdLocalId + "&password=" + password + "&service=" + service + "?manualId=" + manualId + "&treeType=1&enterType="
                                window.open("http://" + url, "_blank", "toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, ");
                            })
                        } else {

                        }
                    }
                })

            })
        }
        /**
         * @ByYQL新增Tab菜单：查看PACS图像
         * Create 2021-11-1
         */
        else if (data.code == "03050049") {   //PACS图像
            var titleData = JSON.parse(sessionStorage.getItem('titleData'));
            this.setState({
                titleData
            }, function () {
                let data = { params: [{}] };
                $http.post('urlS', this, {
                    code: '03010122',
                    data: data,
                    success: function (res) {
                        if (+res.errorCode === 0) {
                            this.handleViewPACSImage(res.result)
                        } else { message.warning(res.errorMessage) }
                    }
                });
            })
        } else {
            this.setState({
                isShowComponentModal: true,
                dataSource: data
            })
        }
        this.handleRecordClickThroughRate(data);
    }

    showTempleteSheet() {
        temperature.previewTemperature(sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "");
        return;
    }

    handleViewPACSImage = (pacsParams) => {
        let dllInput = {};
        dllInput.exeName = pacsParams?.PACSExeName;
        dllInput.parameter = !Util.isEmpty(this.state.titleData) ? this.state.titleData.patNo : '';
        dllInput.path = pacsParams?.PACSPath;
        // console.log(JSON.stringify(dllInput))
        if (typeof (CefSharp) != "undefined") { // 新元素定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            setTimeout(() => {
                xysCefToJavaScripts.driveLocalHardware("{'inputDir':'OpenExe/OpenExe.dll','clsName':'OpenExe.ExeObj','funcName':'CreateProcess','dllInput':'" + JSON.stringify(dllInput) + "'}").then((returnVale) => {
                    console.log(returnVale);
                })
            }, 100);
        } else {
            let dllInput = {};
            dllInput.exeName = pacsParams?.PACSExeName;
            dllInput.parameter = !Util.isEmpty(this.state.titleData) ? this.state.titleData.patNo : '';
            dllInput.path = pacsParams?.PACSPath;
            let data = 'input={"inputDir":"OpenExe/OpenExe.dll","clsName":"OpenExe.ExeObj","funcName":"CreateProcess","dllInput":' + JSON.stringify(dllInput) + '}'
            fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
                jsonpCallback: 'JsonCallback',
                timeout: 30000,
            })
                .then(function (response) {
                    return response.json()
                }).then(function (json) { }).catch(function (ex) { })
        }
    };

    // 记录点击率
    handleRecordClickThroughRate = async (record) => {
        try {
            if (record?.ClickRateFlag !== 'Y') return;
            const patientData = React.$getSessionData('patientData')
            let data = {
                params: [{
                    menuCode: record?.code || '',
                    patID: patientData?.patID || '',
                    admID: patientData?.admID || '',
                }]
            }
            let res = await React.$asyncPost(this, '01040293', data);
            console.log(res)
        } catch (error) {
            console.log(error);
        }
    }

    render() {
        var { doctorData } = this.state;
        var componentOption = []
        //webpack配置有问题，现在只能这样写死图片
        //动态渲染右侧组件
        doctorData && doctorData.map((item, index) => {
            var img = ''
            if (item.code == '03050010') {
                img = records
            } else if (item.code == '03050030') {
                img = inspect
            } else if (item.code == '03050031') {
                img = patho
            } else if (item.code == '03050034') {
                img = textReport
            } else if (item.code == '03050011') {
                img = appointment
            } else if (item.code == '03050032') {
                img = infectious
            } else if (item.code == '03050012') {
                img = hospital
            } else if (item.code == '02050033') {
                img = history
            } else if (item.code == '03050044') {
                img = doctorAdviceFind
            } else if (item.code == '03050045') {
                img = textReport
            } else if (item.code == '03050036') {
                img = diagnosis
            } else if (item.code == '03050038') {
                img = information
            } else if (item.code == '03050046') {
                img = resultTarget
            } else if (item.code == '03050047') {
                img = productionBook
            } else if (item.code == '03050050') {
                img = productionBook
            } else if (item.code == '03050061') {
                img = productionBook
            } else if (item.code == '03050063') {
                img = appointment
            } else if (item.code == 'UnifiedAppointment') {
                img = appointment
            } else if (item.code == '03050081') {
                img = appointment
            } else if (item.code == '03050082') {
                img = temperate
            } else if (item.code == '03050087') {
                img = textReport
            } else if (item.code == '04160001') {    //手术申请
                img = surgicalapply
            } else if (item.code == '03050049') {    //PACS图像
                img = pacsimg
            } else if (item.code == 'OptometryInquiry') {    //验光结果
                img = textReport
            } else {
                img = textReport
            }
            componentOption.push(
                <Tooltip key={index} title={this.state.userData.language == 'EN' ? (item.ENDesc ? item.ENDesc : item.title) : item.title}
                    placement='left'>
                    {item.code == '03050082' ? <Button className='common-btn-style' key={index} style={{ height: 70, margin: '3px' }} size='small'
                        disabled={Util.isEmpty(this.props.patientData) ? true : false}
                        onClick={this.showTempleteSheet.bind(this, item)}>
                        <div><img style={{ marginTop: 10 }} src={img} /></div>
                        <span style={{ padding: '5px 0', width: "70px", textOverflow: "ellipsis", overflow: "hidden" }}>
                            {this.state.userData.language == 'EN' ? (item.ENDesc ? item.ENDesc : item.title) : item.title}</span></Button> :
                        <Button className='common-btn-style' key={index} style={{ height: 70, margin: '3px' }} size='small'
                            disabled={Util.isEmpty(this.props.patientData) ? true : false}
                            onClick={this.showComponentModal.bind(this, item)}>
                            <div><img style={{ marginTop: 10 }} src={img} /></div>
                            <span style={{ padding: '5px 0', width: "70px", textOverflow: "ellipsis", overflow: "hidden" }}>
                                {this.state.userData.language == 'EN' ? (item.ENDesc ? item.ENDesc : item.title) : item.title}</span></Button>}</Tooltip>)
        })
        return <div className='patient-step' style={{ height: 'calc(100% - 80px)', display: this.props.display }}>
            {/**公共组件弹框 */}
            <ShowComponentModal isShow={this.state.isShowComponentModal}
                dataSource={this.state.dataSource}
                onHide={this.hideModal.bind(this, 'isShowComponentModal')} />
            {componentOption}
        </div>
    }
};